// 首页帖子列表功能
$(document).ready(function() {
    // 检查登录状态，如果未登录则重定向到登录页
    const token = localStorage.getItem('jwt_token');
    if (!token) {
        window.location.href = 'login.html';
        return;
    }

    let currentPage = 1;
    let currentCategory = 'all';
    let currentSort = getQueryParam('sort') || 'latest';
    let totalPages = 1;

    // 加载帖子列表
    function loadPosts(page = 1, category = 'all', sort = 'latest') {
        let url;
        
        if (sort === 'hot') {
            // 使用热门帖子接口
            url = `/posts/hot?page=${page}&limit=10`;
        } else if (sort === 'featured') {
            // 使用精华帖子接口
            url = `/posts/featured?page=${page}&limit=10`;
        } else {
            // 使用普通帖子接口，添加排序参数
            url = `/posts?page=${page}&limit=10`;
            
            // 添加排序参数
            if (sort === 'latest') {
                url += '&sort=createTime&order=desc';
            }
        }
        
        if (category !== 'all') {
            url += `&categoryId=${category}`;
        }

        request({
            url: url,
            method: 'GET',
            success: function(response) {
                if ( response.data) {
                    renderPosts(sort === 'hot' ?response.data : response.data.records);
                    updatePagination(response.data.pagination);
                } else {
                    showError('加载帖子失败');
                }
            },
            error: function() {
                showError('网络错误，请稍后重试');
            }
        });
    }

    // 渲染帖子列表
    function renderPosts(posts) {
        const $postList = $('#post-list');
        $postList.empty();

        if (posts.length === 0) {
            $postList.html('<div class="post-card" style="text-align: center; padding: 40px; color: #666;">暂无帖子</div>');
            return;
        }

        posts.forEach(post => {
            // 检查是否为精华帖子
            const isFeatured = post.isFeatured === 1;
            const featuredBadge = isFeatured ? '<span class="featured-badge" style="background: #e74c3c; color: white; padding: 2px 8px; border-radius: 12px; font-size: 12px; margin-right: 8px; font-weight: bold;">精华</span>' : '';
            
            const postHtml = `
                <div class="post-card">
                    <h3 class="post-title">
                        ${featuredBadge}
                        <a href="post.html?id=${post.id}">${escapeHtml(post.title)}</a>
                    </h3>
                    <div class="post-meta">
                        <span class="author">${escapeHtml(post.nickname || '匿名用户')}</span>
                        <span class="time">${formatDateTime(post.createTime)}</span>
                        <span class="category">${getCategoryName(post.categoryId)}</span>
                    </div>
                    <div class="post-stats">
                        <span class="likes">👍 ${post.likeCount || 0}</span>
                        <span class="comments">💬 ${post.commentCount || 0}</span>
                        <span class="views">👁️ ${post.viewCount || 0}</span>
                    </div>
                </div>
            `;
            $postList.append(postHtml);
        });
    }

    // 更新分页控件
    function updatePagination(pagination) {
        const $pagination = $('.pagination');
        $pagination.empty();

        if (pagination.totalPages <= 1) {
            return;
        }

        // 上一页按钮
        if (pagination.currentPage > 1) {
            $pagination.append('<a href="#" class="prev">上一页</a>');
        }

        // 页码按钮
        for (let i = 1; i <= pagination.totalPages; i++) {
            const activeClass = i === pagination.currentPage ? 'active' : '';
            $pagination.append(`<a href="#" class="page ${activeClass}" data-page="${i}">${i}</a>`);
        }

        // 下一页按钮
        if (pagination.currentPage < pagination.totalPages) {
            $pagination.append('<a href="#" class="next">下一页</a>');
        }

        // 绑定分页点击事件
        $pagination.find('a').on('click', function(e) {
            e.preventDefault();
            const $this = $(this);
            
            if ($this.hasClass('prev')) {
                loadPosts(currentPage - 1, currentCategory, currentSort);
            } else if ($this.hasClass('next')) {
                loadPosts(currentPage + 1, currentCategory, currentSort);
            } else if ($this.hasClass('page')) {
                loadPosts(parseInt($this.data('page')), currentCategory, currentSort);
            }
        });
    }

    // 获取分类名称
    function getCategoryName(categoryId) {
        const categories = {
            '1': '学习交流',
            '2': '校园生活',
            '3': '二手交易',
            '4': '社团活动',
            '5': '其他'
        };
        return categories[categoryId] || '未知分类';
    }

    // HTML转义函数
    function escapeHtml(text) {
        const map = {
            '&': '&',
            '<': '<',
            '>': '>',
            '"': '"',
            "'": '&#039;'
        };
        return text.replace(/[&<>"']/g, function(m) { return map[m]; });
    }

    // 分类点击事件
    $('#category-list a').on('click', function(e) {
        e.preventDefault();
        const category = $(this).data('category');
        currentCategory = category;
        currentPage = 1;
        loadPosts(currentPage, currentCategory, currentSort);
        
        // 更新选中状态
        $('#category-list a').removeClass('active');
        $(this).addClass('active');
    });

    // 更新导航栏高亮状态
    function updateNavHighlight() {
        const sort = getQueryParam('sort') || 'latest';
        $('.nav-menu a').removeClass('active');
        
        if (sort === 'latest') {
            $('.nav-menu a[href*="sort=latest"]').addClass('active');
        } else if (sort === 'hot') {
            $('.nav-menu a[href*="sort=hot"]').addClass('active');
        } else if (sort === 'featured') {
            $('.nav-menu a[href*="sort=featured"]').addClass('active');
        } else {
            $('.nav-menu a[href="index.html"]').addClass('active');
        }
    }

    // 加载论坛统计信息
    function loadStatistics() {
        request({
            url: '/statistics',
            method: 'GET',
            success: function(response) {
                if ( response.data) {
                    $('#today-posts').text(response.data.todayPosts || 0);
                    $('#total-posts').text(response.data.totalPosts || 0);
                    $('#total-users').text(response.data.totalUsers || 0);
                }
            },
            error: function() {
                console.error('加载统计信息失败');
            }
        });
    }

    // 初始化页面
    function initPage() {
        // 从URL参数获取排序方式和分类
        const urlSort = getQueryParam('sort');
        const urlCategory = getQueryParam('category');
        
        if (urlSort) {
            currentSort = urlSort;
        }
        if (urlCategory) {
            currentCategory = urlCategory;
        }
        
        loadPosts(currentPage, currentCategory, currentSort);
        loadStatistics();
        updateNavHighlight();
        
        // 更新分类选中状态
        if (currentCategory !== 'all') {
            $(`#category-list a[data-category="${currentCategory}"]`).addClass('active');
        } else {
            $('#category-list a[data-category="all"]').addClass('active');
        }
        
        // 检查用户权限，显示/隐藏发布按钮
        const userInfo = localStorage.getItem('user_info');
        if (userInfo) {
            try {
                const user = JSON.parse(userInfo);
                if (user.role === 'banned') {
                    $('#create-post-btn').hide();
                }
            } catch (e) {
                console.error('解析用户信息失败');
            }
        }
    }

    // 启动页面初始化
    initPage();
});
